package com.yan.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
// 加上这个注解，使得支持事务
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {

    // http://www.cnblogs.com/zhuxiaojie/p/5836159.html

    @Autowired
    private DruidConfig druidConfig;

    public DataSource getDataSource() {
        return druidConfig.dataSource();
    }

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(getDataSource());
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();

        try {
            sessionFactoryBean.setDataSource(getDataSource());
            //https://www.cnblogs.com/dannyyao/p/7736246.html
            sessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);  //下划线与驼峰自动转
            //  PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            //sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/**/*.xml"));

            return sessionFactoryBean.getObject();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Bean
    public SqlSessionTemplate sqlSessionTemplate() {
        return new SqlSessionTemplate(sqlSessionFactoryBean());
    }


}